package live.zs.securitytokenauthorize.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author madison
 * @description
 * @date 2021/7/17 12:42
 */
@Configuration
public class CaffeineConfig {

    private static final int DEFAULT_MAXSIZE = 1000;

    @Bean
    CacheManager cacheManager() {
//        SimpleCacheManager manager = new SimpleCacheManager();
//        //把各个cache注册到cacheManager中，CaffeineCache实现了org.springframework.cache.Cache接口
//        ArrayList<CaffeineCache> caches = new ArrayList<>();
//        for (Caches c : Caches.values()) {
//            CaffeineCache caffeineCache = new CaffeineCache(c.name(),
//                    Caffeine.newBuilder().recordStats()
//                            .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
//                            .maximumSize(c.getMaxSize())
//                            .build());
//            caches.add(caffeineCache);
//        }
//        manager.setCaches(caches);

        CaffeineCacheManager manager = new CaffeineCacheManager();
        for (Caches cache : Caches.values()) {
            //把各个cache注册到cacheManager中
            manager.registerCustomCache(cache.name(), Caffeine.newBuilder().recordStats()
                    .expireAfterWrite(cache.getTtl(), TimeUnit.SECONDS)
                    .maximumSize(cache.getMaxSize()).build());
        }

        return manager;
    }

    /**
     * 定义cache名称、超时时长秒、最大个数
     * 每个cache缺省3600秒过期，最大个数1000
     */
    private enum Caches {
        jwtToken(5, DEFAULT_MAXSIZE),
        userDetails(30, DEFAULT_MAXSIZE);

        private int maxSize;    //最大數量
        private int ttl;        //过期时间（秒）

        Caches(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        public int getMaxSize() {
            return maxSize;
        }

        public int getTtl() {
            return ttl;
        }
    }
}
